#!/usr/local/bin/python
# -*- coding: utf-8 -*-

'''
用于处理【利润表（收支表）】逻辑. IncomeStatement
'''

from datetime import datetime

from PyQt5.QtWidgets import QWidget, QAbstractItemView, QTableWidgetItem
from dateutil.relativedelta import relativedelta
from PyQt5 import QtWidgets
from xToolkit import xstring

import init
import initIncomeStatementPage
import toolkit
from IncomeStatement import IncomeStatement
from IncomeStatementDetailDialog import IncomeStatementDetailDialog

from initLogger import logger
#from ui.IncomeStatementUI import Ui_IncomeStatement
from ui.IncomeStatementUI_relative_layout_ import Ui_IncomeStatement


class IncomeStatementWidget(QWidget, Ui_IncomeStatement):
    def __init__(self):
        super(IncomeStatementWidget, self).__init__()
        self.setupUi(self)

        self.currentDate = datetime.now()  #记录当前事件
        self.targetDate = self.currentDate  - relativedelta(days=init.GO_DAYS)#记录当前系统查看数据的时间

        self.initIncomeStatement()


    def initIncomeStatement(self):
        '''
        函数功能：对收支表页面进行初始化
        :return:
        '''

        self.initIncomeStatementUI()
        self.initIncomeStatementTableUI()
        self.initIncomeStatementTableData()

    def initIncomeStatementTitleUI(self):
        incomeStatementTitleStr="%d年%d月——收支表"%(self.targetDate.year, self.targetDate.month)
        self.title_label.setText(incomeStatementTitleStr)

    def initIncomeStatementUI(self):

        self.initIncomeStatementTitleUI()

        #初始化查询模块相关控件
        self.year_comboBox.addItems(init.YEAR_NAME_LIST)
        self.month_comboBox.addItems(init.MONTH_NAME_LIST)
        self.year_comboBox.setCurrentText(str(self.targetDate.year))
        self.month_comboBox.setCurrentText(str(self.targetDate.month))

    def initIncomeStatementTableUI(self):
        '''
        函数功能：初始化资产负债资产表的UI
        :return:
        '''
        self.initIncomeTableUI()
        self.initExpenditureTableUI()
        self.initInvestmentTableUI()

    def initIncomeTableUI(self):
        '''
        函数功能：初始化收入表的UI
        :return:
        '''
        self.income_tableWidget.setRowCount(initIncomeStatementPage.INCOME_STATEMENT_ROW_COUNT)  # 设置行数目
        self.income_tableWidget.setColumnCount(initIncomeStatementPage.INCOME_STATEMENT_COLUMN_COUNT)  # 设置列数目
        self.income_tableWidget.setHorizontalHeaderLabels(initIncomeStatementPage.INCOME_STATEMENT_COLUMN_CONTEXT)
        self.income_tableWidget.setColumnWidth(0, 200)
        self.income_tableWidget.setColumnWidth(1, 200)
        self.income_tableWidget.setColumnWidth(2, 200)

        self.income_tableWidget.resizeRowsToContents()  # 设置行宽自适应
        self.income_tableWidget.resizeColumnsToContents()  # 设置列宽自适应
        self.income_tableWidget.setShowGrid(True)  # 设置显示网络线
        self.income_tableWidget.setAlternatingRowColors(True)  # 设置表格颜色交错显示
        self.income_tableWidget.verticalHeader().setVisible(False)  # 隐藏垂直标题
        self.income_tableWidget.horizontalHeader().setStretchLastSection(True)  # 设置最后一列自动填充容

        self.income_tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows)  # 设置选中整行
        self.income_tableWidget.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)  # 禁止编辑单元格

    def initExpenditureTableUI(self):
        '''
        函数功能：初始化支出表的UI
        :return:
        '''
        self.expenditure_tableWidget.setRowCount(initIncomeStatementPage.INCOME_STATEMENT_ROW_COUNT)  # 设置行数目
        self.expenditure_tableWidget.setColumnCount(initIncomeStatementPage.INCOME_STATEMENT_COLUMN_COUNT)  # 设置列数目
        self.expenditure_tableWidget.setHorizontalHeaderLabels(initIncomeStatementPage.INCOME_STATEMENT_COLUMN_CONTEXT)

        self.expenditure_tableWidget.resizeRowsToContents()  # 设置行宽自适应
        self.expenditure_tableWidget.resizeColumnsToContents()  # 设置列宽自适应
        self.expenditure_tableWidget.setShowGrid(True)  # 设置显示网络线
        self.expenditure_tableWidget.setAlternatingRowColors(True)  # 设置表格颜色交错显示
        self.expenditure_tableWidget.verticalHeader().setVisible(False)  # 隐藏垂直标题
        self.expenditure_tableWidget.horizontalHeader().setStretchLastSection(True)  # 设置最后一列自动填充容

        self.expenditure_tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows)  # 设置选中整行
        self.expenditure_tableWidget.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)  # 禁止编辑单元格

    def initInvestmentTableUI(self):
        '''
        函数功能：初始化支出表的UI
        :return:
        '''
        self.investment_tableWidget.setRowCount(initIncomeStatementPage.INCOME_STATEMENT_ROW_COUNT)  # 设置行数目
        self.investment_tableWidget.setColumnCount(initIncomeStatementPage.INCOME_STATEMENT_COLUMN_COUNT)  # 设置列数目
        self.investment_tableWidget.setHorizontalHeaderLabels(initIncomeStatementPage.INCOME_STATEMENT_COLUMN_CONTEXT)

        self.investment_tableWidget.resizeRowsToContents()  # 设置行宽自适应
        self.investment_tableWidget.resizeColumnsToContents()  # 设置列宽自适应
        self.investment_tableWidget.setShowGrid(True)  # 设置显示网络线
        self.investment_tableWidget.setAlternatingRowColors(True)  # 设置表格颜色交错显示
        self.investment_tableWidget.verticalHeader().setVisible(False)  # 隐藏垂直标题
        self.investment_tableWidget.horizontalHeader().setStretchLastSection(True)  # 设置最后一列自动填充容

        self.investment_tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows)  # 设置选中整行
        self.investment_tableWidget.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)  # 禁止编辑单元格

    def initIncomeStatementTableData(self):
        '''
        函数功能：初始化资产负债表数据
        :return:
        '''
        logger.debug("call initIncomeStatementTableData")

        #展示收入表
        subjectPath = initIncomeStatementPage.INCOME_STATEMENT_LIST["收入"]
        incomeStatement = IncomeStatement(self.targetDate.year, self.targetDate.month)
        incomeStatementResult = incomeStatement.getIncomeStatementDataMonthly(subjectPath)
        self.showIncomeGroupData(incomeStatementResult)

        # 展示支出表
        subjectPath = initIncomeStatementPage.INCOME_STATEMENT_LIST["支出"]
        incomeStatement = IncomeStatement(self.targetDate.year, self.targetDate.month)
        incomeStatementResult = incomeStatement.getIncomeStatementDataMonthly(subjectPath)
        self.showExpenditureGroupData(incomeStatementResult)

        # 展示投资表
        subjectPath = initIncomeStatementPage.INCOME_STATEMENT_LIST["投资"]
        incomeStatement = IncomeStatement(self.targetDate.year, self.targetDate.month)
        incomeStatementResult = incomeStatement.getIncomeStatementDataMonthly(subjectPath)
        self.showInvestmentGroupData(incomeStatementResult)

        self.income_tableWidget.setColumnWidth(0, 180)
        self.income_tableWidget.setColumnWidth(1, 180)
        self.income_tableWidget.setColumnWidth(2, 180)

        self.expenditure_tableWidget.setColumnWidth(0, 180)
        self.expenditure_tableWidget.setColumnWidth(1, 180)
        self.expenditure_tableWidget.setColumnWidth(2, 180)

        self.investment_tableWidget.setColumnWidth(0, 180)
        self.investment_tableWidget.setColumnWidth(1, 180)
        self.investment_tableWidget.setColumnWidth(2, 180)

        self.income_tableWidget.resizeRowsToContents()
        self.expenditure_tableWidget.resizeRowsToContents()
        self.investment_tableWidget.resizeRowsToContents()

    def showInvestmentGroupData(self, incomeStatementGroupResult):
        '''
        函数功能：展示投资数据
        :param incomeStatementGroupResult:
        :return:
        '''

        currentMonthSummation=0.0
        totalSummation=0.0
        length = len(incomeStatementGroupResult)

        for i in range(length):
            dataRow = incomeStatementGroupResult[i]

            subjectPathName = toolkit.getVoucherTail(dataRow.suject_name)
            sebjectPathWidgetItem = QTableWidgetItem(subjectPathName)
            self.investment_tableWidget.setItem(i, 0, sebjectPathWidgetItem)

            currentMonthValue = xstring.dispose(toolkit.processValueSignificant(dataRow.current_month_value)).humanized_amount(complex=True)
            currentMonthSummation = currentMonthSummation + dataRow.current_month_value
            currentMonthValueWidgetItem = QTableWidgetItem(currentMonthValue)
            self.investment_tableWidget.setItem(i, 1, currentMonthValueWidgetItem)

            totalValue = xstring.dispose(toolkit.processValueSignificant(dataRow.total_value)).humanized_amount(complex=True)
            totalSummation = totalSummation + dataRow.total_value
            totalValueWidgetItem = QTableWidgetItem(totalValue)
            self.investment_tableWidget.setItem(i, 2, totalValueWidgetItem)

        sebjectPathWidgetItem = QTableWidgetItem("投资收支合计")
        self.investment_tableWidget.setItem(length, 0, sebjectPathWidgetItem)

        currentMonthValue = xstring.dispose(toolkit.processValueSignificant(currentMonthSummation)).humanized_amount(complex=True)
        currentMonthValueWidgetItem = QTableWidgetItem(currentMonthValue)
        self.investment_tableWidget.setItem(length, 1, currentMonthValueWidgetItem)

        totalValue = xstring.dispose(toolkit.processValueSignificant(totalSummation)).humanized_amount(complex=True)
        totalValueWidgetItem = QTableWidgetItem(totalValue)
        self.investment_tableWidget.setItem(length, 2, totalValueWidgetItem)

        self.investment_tableWidget.resizeRowsToContents()
        #self.investment_tableWidget.resizeColumnsToContents()


    def showExpenditureGroupData(self, incomeStatementGroupResult):
        '''
        函数功能：展示支出数据
        :param incomeStatementGroupResult:
        :return:
        '''

        currentMonthSummation=0.0
        totalSummation=0.0
        length = len(incomeStatementGroupResult)

        if (length+1>initIncomeStatementPage.INCOME_STATEMENT_ROW_COUNT):
            self.expenditure_tableWidget.setRowCount(length+1)

        for i in range(length):
            dataRow = incomeStatementGroupResult[i]

            subjectPathName = toolkit.getVoucherTail(dataRow.suject_name)
            sebjectPathWidgetItem = QTableWidgetItem(subjectPathName)
            self.expenditure_tableWidget.setItem(i, 0, sebjectPathWidgetItem)

            currentMonthValue = xstring.dispose(toolkit.processValueSignificant(dataRow.current_month_value)).humanized_amount(complex=True)
            currentMonthSummation = currentMonthSummation + dataRow.current_month_value
            currentMonthValueWidgetItem = QTableWidgetItem(currentMonthValue)
            self.expenditure_tableWidget.setItem(i, 1, currentMonthValueWidgetItem)

            totalValue = xstring.dispose(toolkit.processValueSignificant(dataRow.total_value)).humanized_amount(complex=True)
            totalSummation = totalSummation + dataRow.total_value
            totalValueWidgetItem = QTableWidgetItem(totalValue)
            self.expenditure_tableWidget.setItem(i, 2, totalValueWidgetItem)

        sebjectPathWidgetItem = QTableWidgetItem("支出合计")
        self.expenditure_tableWidget.setItem(length, 0, sebjectPathWidgetItem)

        currentMonthValue = xstring.dispose(toolkit.processValueSignificant(currentMonthSummation)).humanized_amount(complex=True)
        currentMonthValueWidgetItem = QTableWidgetItem(currentMonthValue)
        self.expenditure_tableWidget.setItem(length, 1, currentMonthValueWidgetItem)

        totalValue = xstring.dispose(toolkit.processValueSignificant(totalSummation)).humanized_amount(complex=True)
        totalValueWidgetItem = QTableWidgetItem(totalValue)
        self.expenditure_tableWidget.setItem(length, 2, totalValueWidgetItem)

        self.expenditure_tableWidget.resizeRowsToContents()
        #self.expenditure_tableWidget.resizeColumnsToContents()



    def showIncomeGroupData(self, incomeStatementGroupResult):
        '''
        函数功能：展示收入数据
        :param incomeStatementGroupResult:
        :return:
        '''

        currentMonthSummation=0.0
        totalSummation=0.0
        length = len(incomeStatementGroupResult)

        for i in range(length):
            dataRow = incomeStatementGroupResult[i]

            subjectPathName = toolkit.getVoucherTail(dataRow.suject_name)
            sebjectPathWidgetItem = QTableWidgetItem(subjectPathName)
            self.income_tableWidget.setItem(i, 0, sebjectPathWidgetItem)

            currentMonthValue = xstring.dispose(toolkit.processValueSignificant(dataRow.current_month_value)).humanized_amount(complex=True)
            currentMonthSummation = currentMonthSummation + dataRow.current_month_value
            currentMonthValueWidgetItem = QTableWidgetItem(currentMonthValue)
            self.income_tableWidget.setItem(i, 1, currentMonthValueWidgetItem)

            totalValue = xstring.dispose(toolkit.processValueSignificant(dataRow.total_value)).humanized_amount(complex=True)
            totalSummation = totalSummation + dataRow.total_value
            totalValueWidgetItem = QTableWidgetItem(totalValue)
            self.income_tableWidget.setItem(i, 2, totalValueWidgetItem)

        sebjectPathWidgetItem = QTableWidgetItem("收入合计")
        self.income_tableWidget.setItem(length, 0, sebjectPathWidgetItem)

        currentMonthValue = xstring.dispose(toolkit.processValueSignificant(currentMonthSummation)).humanized_amount(complex=True)
        currentMonthValueWidgetItem = QTableWidgetItem(currentMonthValue)
        self.income_tableWidget.setItem(length, 1, currentMonthValueWidgetItem)

        totalValue = xstring.dispose(toolkit.processValueSignificant(totalSummation)).humanized_amount(complex=True)
        totalValueWidgetItem = QTableWidgetItem(totalValue)
        self.income_tableWidget.setItem(length, 2, totalValueWidgetItem)

        self.income_tableWidget.resizeRowsToContents()
        #self.income_tableWidget.resizeColumnsToContents()

    def clearIncomeStatementTableContext(self):
        '''
        函数功能：清空收支表表格数据
        :return:
        '''
        self.income_tableWidget.clear()
        self.expenditure_tableWidget.clear()
        self.investment_tableWidget.clear()

    def onSearch(self):
        '''
        函数功能：处理查询响应函数
        :return:
        '''

        year = int(self.year_comboBox.currentText())
        month = int(self.month_comboBox.currentText())
        self.targetDate = toolkit.setTargetDate(year, month)

        self.clearIncomeStatementTableContext()
        self.initIncomeStatement()


    def onGoLastMonth(self):
        """
        函数功能；展示上一个月的收支表数据
        :return:
        """

        self.targetDate = toolkit.getLastMonth(self.targetDate, number=1)
        logger.debug("target year: %d   month: %d" % (self.targetDate.year, self.targetDate.month))
        self.clearIncomeStatementTableContext()

        self.year_comboBox.setCurrentText(str(self.targetDate.year))
        self.month_comboBox.setCurrentText(str(self.targetDate.month))

        self.initIncomeStatement()






    def onGoNextMonth(self):
        """
        函数功能；展示下一个月的收支表
        :return:
        """
        self.targetDate = toolkit.getNextMonth(self.targetDate, number=1)
        logger.debug("target year: %d   month: %d" % (self.targetDate.year, self.targetDate.month))
        self.clearIncomeStatementTableContext()

        self.year_comboBox.setCurrentText(str(self.targetDate.year))
        self.month_comboBox.setCurrentText(str(self.targetDate.month))

        self.initIncomeStatement()

    def onUpdateIncomeStatement(self):
        '''
        函数功能：更新记账簿数据
        :return:
        '''
        logger.debug("call onUpdateIncomeStatement")


        incomeStatement = IncomeStatement(self.targetDate.year, self.targetDate.month)
        incomeStatement.genIncomeStatement()

        self.clearIncomeStatementTableContext()
        self.initIncomeStatement()


    def onUpdateAllYearIncomeStatement(self):
        '''
        函数功能：更新全年记账簿数据
        :return:
        '''
        pass


    '''
        self.income_tableWidget.setColumnWidth(0, 180)
        self.income_tableWidget.setColumnWidth(1, 180)
        self.income_tableWidget.setColumnWidth(2, 180)

        self.expenditure_tableWidget.setColumnWidth(0, 180)
        self.expenditure_tableWidget.setColumnWidth(1, 180)
        self.expenditure_tableWidget.setColumnWidth(2, 180)

        self.investment_tableWidget.setColumnWidth(0, 180)
        self.investment_tableWidget.setColumnWidth(1, 180)
        self.investment_tableWidget.setColumnWidth(2, 180)
    '''


    def onIncomeTableDoubleClicked(self):
        '''
        函数功能：收支表收入表双击事件响应函数
        :return:
        '''
        logger.debug("call onIncomeTableDoubleClicked function")
        selectRow = self.income_tableWidget.selectedItems()[0].row()
        selectText = self.income_tableWidget.selectedItems()[0].text().strip('\t')


        incomeStatementDetailDialog = IncomeStatementDetailDialog(parent=self,
                                                            selectRow=selectRow,
                                                            selectText=selectText,
                                                            year=self.targetDate.year,
                                                            month=self.targetDate.month)
        #balanceSheetDetailDialog.setWindowFlags(QtCore.Qt.WindowCloseButtonHint)
        if incomeStatementDetailDialog.exec_():
            pass
        incomeStatementDetailDialog.destroy()




    def onExpenseTableDoubleClicked(self):
        '''
        函数功能：收支表支出表双击事件响应函数
        :return:
        '''

        logger.debug("call onExpenseTableDoubleClicked function")
        selectRow = self.expenditure_tableWidget.selectedItems()[0].row()
        selectText = self.expenditure_tableWidget.selectedItems()[0].text().strip('\t')


        incomeStatementDetailDialog = IncomeStatementDetailDialog(parent=self,
                                                            selectRow=selectRow,
                                                            selectText=selectText,
                                                            year=self.targetDate.year,
                                                            month=self.targetDate.month)

        #balanceSheetDetailDialog.setWindowFlags(QtCore.Qt.WindowCloseButtonHint)

        if incomeStatementDetailDialog.exec_():
            pass
        incomeStatementDetailDialog.destroy()
    def onInvestmentTableDoubleClicked(self):
        '''
        函数功能；收支表投资收支表双击事件响应函数
        :return:
        '''
        logger.debug("call onInvestmentTableDoubleClicked function")
        selectRow = self.investment_tableWidget.selectedItems()[0].row()
        selectText = self.investment_tableWidget.selectedItems()[0].text().strip('\t')


        incomeStatementDetailDialog = IncomeStatementDetailDialog(parent=self,
                                                            selectRow=selectRow,
                                                            selectText=selectText,
                                                            year=self.targetDate.year,
                                                            month=self.targetDate.month)

        #balanceSheetDetailDialog.setWindowFlags(QtCore.Qt.WindowCloseButtonHint)

        if incomeStatementDetailDialog.exec_():
            pass
        incomeStatementDetailDialog.destroy()

def main():
    pass


if __name__ == '__main__':
    main()